package com.dyz.leetcode._18_backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _40_combinationSum2 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] visited = new boolean[candidates.length];
        Arrays.sort(candidates);
        dfs(candidates, 0, target, path, res, visited);
        return res;

    }

    private void dfs(int[] nums,
                     int index,
                     int target,
                     List<Integer> path,
                     List<List<Integer>> res,
                     boolean[] visited){

        if(target<=0){
            if(target==0){
                res.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i=index; i<nums.length; i++){
            if (visited[i]){continue;}
            if(i>index && nums[i]==nums[i-1]){continue;}
            path.add(nums[i]);
            visited[i] = true;
            dfs(nums, i+1, target-nums[i], path, res, visited);
            path.remove(path.size()-1);
            visited[i] = false;
            }
        }

}
